package com.dalongxin.work.page;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;

import com.andview.refreshview.XRefreshView;
import com.dalongxin.work.Constants;
import com.dalongxin.work.R;
import com.dalongxin.work.data.Company;
import com.dalongxin.work.data.Department;
import com.dalongxin.work.data.Project;
import com.dalongxin.work.data.SelectionBase;
import com.dalongxin.work.page.adapter.selection.ChildrenCategoryAdapter;
import com.dalongxin.work.page.adapter.selection.ParentCategoryAdapter;
import com.dalongxin.work.utils.HttpUtil;
import com.dalongxin.work.utils.StatusBarUtil;
import com.dalongxin.work.utils.ToastUtil;

import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.common.util.LogUtil;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@ContentView(R.layout.activity_selection)
public class SelectionActivity extends BaseActivity implements View.OnClickListener {

    @ViewInject(R.id.tool_bar)
    private Toolbar toolbar;
    @ViewInject(R.id.title_back)
    private ImageButton titleBack;
    @ViewInject(R.id.title_text)
    private TextView titleText;
    @ViewInject(R.id.submit)
    private TextView submit;

    @ViewInject(R.id.lv_parent_category)
    private ListView parentListView;
    @ViewInject(R.id.xrefreshview)
    private XRefreshView xRefreshView;
    @ViewInject(R.id.lv_children_category)
    private ListView childListView;

    public static final String SELECT_TYPE = "SELECT_TYPE";
    private int selectType;

    private SelectCategory selectCategory;
    private ParentCategoryAdapter parentCategoryAdapter;
    private ChildrenCategoryAdapter childrenCategoryAdapter;
    private String[] htspSelection = new String[] {"公司", "项目", "所属"};
    private String[] htspSelection1 = new String[] {"公司", "部门", "所属"};

    private List<List<SelectionBase>> mChildList;
    private List<SelectionBase> companyList;
    private List<SelectionBase> projectList;
    private List<SelectionBase> departmentList;
    private List<SelectionBase> suoshuList = new ArrayList<>();

    private int parentPosition = 0;
    private Map<Integer, Integer> chooseMap = new HashMap<>();

    public static final int REQ_SELECT = 1988;
    public static final String SELECT_PARAMS = "select_params";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);
        //this.setSupportActionBar(toolbar);//这样menu才能显示出来【自定义toolbar的话 这个不要设置】
        //getSupportActionBar().setDisplayShowTitleEnabled(false);//去掉默认title的显示
        StatusBarUtil.setPaddingSmart(this, toolbar);
        StatusBarUtil.darkMode(this, false);
        titleText.setText("筛选条件");
        titleBack.setOnClickListener(this);
        submit.setOnClickListener(this);

        selectType = getIntent().getIntExtra(SELECT_TYPE, 0);
        mChildList = new ArrayList<>();
        companyList = spUtils.getListData(Constants.Key.SP_COMPANY, SelectionBase.class);
        if(companyList == null || companyList.size() == 0) {
            companyList = new ArrayList<>();
            getCompanyList();
        }
        if(selectType == 0) {
            projectList = spUtils.getListData(Constants.Key.SP_PROJECT, SelectionBase.class);
            if (projectList == null || projectList.size() == 0) {
                projectList = new ArrayList<>();
                getProjectList();
            }
        }else {
            departmentList = spUtils.getListData(Constants.Key.SP_DEPARTMENT, SelectionBase.class);
            if (departmentList == null || departmentList.size() == 0) {
                departmentList = new ArrayList<>();
                getDepartmentList();
            }
        }
        SelectionBase suoshu0 = new SelectionBase();
        suoshu0.setId(0);
        suoshu0.setName("所有的");
        SelectionBase suoshu1 = new SelectionBase();
        suoshu1.setId(1);
        suoshu1.setName("需要我审核的");
        SelectionBase suoshu2 = new SelectionBase();
        suoshu2.setId(2);
        suoshu2.setName("我创建的");
        suoshuList.add(suoshu0);
        suoshuList.add(suoshu1);
        suoshuList.add(suoshu2);

        if(selectType == 0) {
            mChildList.add(0, companyList);
            mChildList.add(1, projectList);
            mChildList.add(2, suoshuList);
        }else {
            mChildList.add(0, companyList);
            mChildList.add(1, departmentList);
            mChildList.add(2, suoshuList);
        }
        //一开始是全是空的
        chooseMap.put(0, -1);
        chooseMap.put(1, -1);
        chooseMap.put(2, -1);
        selectCategory = new SelectCategory() {
            @Override
            public void selectCategory(int parentSelectposition,int childrenSelectposition) {
                //String parent = htspSelection[parentSelectposition];
                int id = 0;
                parentPosition = parentSelectposition;
                List<SelectionBase> children = mChildList.get(parentSelectposition);
                if(children != null) {
                    for(int i = 0; i < children.size(); i++) {
                        SelectionBase child = children.get(i);
                        if(i == childrenSelectposition) {
                            child.setChecked(true);
                            id = child.getId();
                        }else {
                            child.setChecked(false);
                        }
                    }
                }
                chooseMap.put(parentSelectposition, id);
                childrenCategoryAdapter.notifyDataSetChanged();
            }
        };
        if(selectType == 0) {
            parentCategoryAdapter = new ParentCategoryAdapter(this, htspSelection);
        }else {
            parentCategoryAdapter = new ParentCategoryAdapter(this, htspSelection1);
        }
        childrenCategoryAdapter = new ChildrenCategoryAdapter(this);
        childrenCategoryAdapter.setDatas(companyList);
        childrenCategoryAdapter.notifyDataSetChanged();

        parentListView.setAdapter(parentCategoryAdapter);
        childListView.setAdapter(childrenCategoryAdapter);

        parentListView.setOnItemClickListener(parentItemClickListener);
        childListView.setOnItemClickListener(childrenItemClickListener);

        xRefreshView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {
            @Override
            public void onRefresh(boolean isPullDown) {
                if(selectType == 0) {
                    if (parentPosition == 0) {
                        getCompanyList();
                    } else if (parentPosition == 1) {
                        getProjectList();
                    } else {
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                xRefreshView.stopRefresh();
                            }
                        }, 1000);
                    }
                }else {
                    if (parentPosition == 0) {
                        getCompanyList();
                    } else if (parentPosition == 1) {
                        getDepartmentList();
                    } else {
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                xRefreshView.stopRefresh();
                            }
                        }, 1000);
                    }
                }
            }
            @Override
            public void onLoadMore(boolean isSilence) {
            }
        });
        xRefreshView.setPullRefreshEnable(true);//允许下拉刷新
        xRefreshView.setPullLoadEnable(false);//禁止加载更多
        xRefreshView.setAutoRefresh(false);
    }

    /**
     * 子类别点击事件
     */
    private AdapterView.OnItemClickListener childrenItemClickListener = new AdapterView.OnItemClickListener(){
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
            if(selectCategory!=null){
                selectCategory.selectCategory(parentCategoryAdapter.getPos(),position);
            }
        }
    };

    /**
     * 父类别点击事件
     */
    private AdapterView.OnItemClickListener parentItemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
            parentPosition = position;

            childrenCategoryAdapter.setDatas(mChildList.get(position));
            childrenCategoryAdapter.notifyDataSetChanged();

            parentCategoryAdapter.setSelectedPosition(position);
            parentCategoryAdapter.notifyDataSetChanged();
        }
    };

    /**
     * 选择成功回调
     * @author apple
     *
     */
    public interface SelectCategory{
        /**
         * 把选中的下标通过方法回调回来
         * @param parentSelectposition  父类别选中下标
         * @param childrenSelectposition 子类别选中下标
         */
        void selectCategory(int parentSelectposition,int childrenSelectposition);
    }

    private void getCompanyList() {
        Map<String, String> params = new HashMap<>();
        HttpUtil.getInstance().post(true, Constants.url_getCompanyList, params, new Callback.CommonCallback<JSONObject>() {
            @Override
            public void onSuccess(JSONObject response) {
                LogUtil.e("response=" + response);
                if (response.optInt("ret") == 0) {
                    List<Company> temp = Company.parseFromJsonList(response.optJSONArray("data"));
                    if(temp != null) {
                        companyList.clear();
                        companyList.addAll(temp);
                        spUtils.putListData(Constants.Key.SP_COMPANY, companyList);
                        mChildList.remove(0);
                        mChildList.add(0, companyList);

                        childrenCategoryAdapter.setDatas(companyList);
                        childrenCategoryAdapter.notifyDataSetChanged();
                    }
                } else {
                    ToastUtil.showShort(response.optString("msg"));
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {
                xRefreshView.stopRefresh();
            }
        });
    }

    private void getProjectList() {
        Map<String, String> params = new HashMap<>();
        HttpUtil.getInstance().post(true, Constants.url_getProjectList, params, new Callback.CommonCallback<JSONObject>() {
            @Override
            public void onSuccess(JSONObject response) {
                LogUtil.e("response=" + response);
                if (response.optInt("ret") == 0) {
                    List<Project> temp = Project.parseFromJsonList(response.optJSONArray("data"));
                    if(temp != null) {
                        projectList.clear();
                        projectList.addAll(temp);
                        spUtils.putListData(Constants.Key.SP_PROJECT, projectList);
                        mChildList.remove(1);
                        mChildList.add(1, projectList);

                        childrenCategoryAdapter.notifyDataSetChanged();
                    }
                } else {
                    ToastUtil.showShort(response.optString("msg"));
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {
                xRefreshView.stopRefresh();
            }
        });
    }

    private void getDepartmentList() {
        Map<String, String> params = new HashMap<>();
        HttpUtil.getInstance().post(true, Constants.url_contactList, params, new Callback.CommonCallback<JSONObject>() {
            @Override
            public void onSuccess(JSONObject response) {
                LogUtil.e("response=" + response);
                if (response.optInt("ret") == 0) {
                    List<Department> temp = Department.parseFromJsonListInDepartment(response.optJSONArray("data"));
                    if(temp != null) {
                        departmentList.clear();
                        departmentList.addAll(temp);
                        spUtils.putListData(Constants.Key.SP_DEPARTMENT, departmentList);
                        mChildList.remove(1);
                        mChildList.add(1, departmentList);

                        childrenCategoryAdapter.notifyDataSetChanged();
                    }
                } else {
                    ToastUtil.showShort(response.optString("msg"));
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {
                xRefreshView.stopRefresh();
            }
        });
    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.title_back:
                finish();
                break;
            case R.id.submit:
                intent = new Intent();
                intent.putExtra(SELECT_PARAMS, (Serializable)chooseMap);
                setResult(RESULT_OK, intent);
                finish();
                break;
        }
    }
}
